package ltd.hanamaki.review.jdbc.util;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 工具类
 */
public class JDBCUtils_Druid {

    static Connection connection;
    static DataSource dataSource;

    /* 编写 一个 获取数据库连接信息的 方法 */
    static {
        Properties properties = new Properties();
        try {
            /* 加载文件的位置 */
            InputStream resourceAsStream = JDBCUtils_Druid.class.getClassLoader().getResourceAsStream("db_dbcp.properties");
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
        }
    }

    /* 编写 数据库连接 的方法 */
    public static Connection getCon() {
        try {
            connection=  dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    /* 释放资源 */
    public static void release(Connection connection, Statement statement, ResultSet resultSet, PreparedStatement preparedStatement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                System.out.println("sql异常");
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                System.out.println("sql异常");
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                System.out.println("sql异常");
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                System.out.println("sql异常");
            }
        }

    }


}
